/*
 * EdgePropertyDialog.java
 *
 * Created on March 22, 2007, 2:23 PM
 * Copyright 2007 Grotto Networking
 */

package EPDLEditor.UI.Dialogs;

import java.awt.Paint;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

import org.apache.commons.collections15.Transformer;

import EPDLEditor.MainEditor;
import EPDLEditor.Types.Context;
import EPDLEditor.Types.DerivedEvent;
import EPDLEditor.Types.EPADerivation;
import EPDLEditor.Types.EPAFiltering;
import EPDLEditor.Types.EPAPattern;
import EPDLEditor.Types.GraphElements;
import EPDLEditor.Types.ParticipantEvent;
import EPDLEditor.Types.GraphElements.MyVertex;
import EPDLEditor.UI.renderers.VertexColorVisualization;
import EPDLEditor.UI.renderers.TextAreaRenderer;
import EPDLEditor.exceptions.UniqueNameException;

/**
 *
 * @author  Ronen Vaisenberg
 */
public class VertexPropertyDialog extends javax.swing.JDialog {
    GraphElements.MyVertex vertex;
    
    /** Creates new form EdgePropertyDialog */
    public VertexPropertyDialog(java.awt.Frame parent, GraphElements.MyVertex vertex) {
        super(parent, true);
        this.vertex = vertex;

        initComponents();
        this.jAgentIdTextPane.setText(vertex.getAgentId());
        //setTitle(vertex.getName());
        //this.jAgentTypeList.setSelectedValue("Event Processing Agent", true);
        //this.jAgentTypeList.setEnabled(false);
        
        //this.jAgentTypeList.setEnabled(true);
        //this.capFormattedTextField.setValue(edge.getCapacity() );
        //this.wtFormattedTextField.setValue(edge.getWeight());
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jAgentSubTypeComboBox5 = new javax.swing.JComboBox();
        jScrollPane5 = new javax.swing.JScrollPane();
        jPartitionParamsTable = new javax.swing.JTable();
        jAgentDerivationPane = new javax.swing.JScrollPane();
        jDerivationTextArea = new javax.swing.JTextArea();
        jAgentOKButton = new javax.swing.JButton();
        jAgentSelection = new javax.swing.JScrollPane();
        jAgentSelectionTextArea = new javax.swing.JTextArea();
        jAgentSelectionLabel = new javax.swing.JLabel();
        jPatternLabel = new javax.swing.JLabel();
        jDerivationLabel = new javax.swing.JLabel();
        jContextLabel = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jAgentIdTextPane = new javax.swing.JTextPane();
        jAgentSubTypeLabel = new javax.swing.JLabel();
        jAgentSubTypeComboBox = new javax.swing.JComboBox();
        jAgentTypeComboBox = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        jParticipantSetLabel = new javax.swing.JLabel();
        jPatternTypeLabel = new javax.swing.JLabel();
        jAgentPatternTypeComboBox = new javax.swing.JComboBox();
        jRelevanceAssertScrollPane = new javax.swing.JScrollPane();
        jRelevanceAssertionTextArea = new javax.swing.JTextArea();
        jRelevanceLabel = new javax.swing.JLabel();
        jPMatchingComboBox = new javax.swing.JComboBox();
        jPMatchingTextField = new javax.swing.JTextField();
        jMatchingLabel = new javax.swing.JLabel();
        jPatternAnnotationLabel = new javax.swing.JLabel();
        jPatternAnnoScrollPane = new javax.swing.JScrollPane();
        jPatternAnnotationTextArea = new javax.swing.JTextArea();
        jParticipantTableScrollPane = new javax.swing.JScrollPane();
        jParticipantTable = new javax.swing.JTable();
        jDerivedTableScrollPane = new javax.swing.JScrollPane();
        jDerivedTable = new javax.swing.JTable();
        JPatternAssertionLbl = new javax.swing.JLabel();
        jAgentContextComboBox = new javax.swing.JComboBox();
        jMatchingLabel1 = new javax.swing.JLabel();

        jAgentSubTypeComboBox5.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "None", "Consume", "Reuse", "Bounded Reuse" }));
        jAgentSubTypeComboBox5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAgentSubTypeComboBox5ActionPerformed(evt);
            }
        });

        jPartitionParamsTable.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPartitionParamsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Pattern Policy", "Policy Specifics"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jPartitionParamsTable.setDragEnabled(true);
        jPartitionParamsTable.getTableHeader().setReorderingAllowed(false);
        jScrollPane5.setViewportView(jPartitionParamsTable);

        jDerivationTextArea.setColumns(20);
        jDerivationTextArea.setRows(5);
        jAgentDerivationPane.setViewportView(jDerivationTextArea);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Agent Properties");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                KeyTypedHandler(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                keyReleasedHandler(evt);
            }
        });

        jAgentOKButton.setText("OK");
        jAgentOKButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonHandler(evt);
            }
        });

        jAgentSelectionTextArea.setColumns(20);
        jAgentSelectionTextArea.setRows(1);
        jAgentSelectionTextArea.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jAgentSelectionTextAreaMouseClicked(evt);
            }
        });
        jAgentSelection.setViewportView(jAgentSelectionTextArea);

        jAgentSelectionLabel.setText("Filter:");

        jPatternLabel.setText("Pattern:");

        jDerivationLabel.setText("Derivation:");

        jContextLabel.setText("Context:");

        jLabel6.setText("Agent Identifier:");

        jScrollPane3.setViewportView(jAgentIdTextPane);

        jAgentSubTypeLabel.setText("Agent Subtype:");

        jAgentSubTypeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAgentSubTypeComboBoxActionPerformed(evt);
            }
        });

        jAgentTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Producer", "Consumer", "Event Processing Agent", "Global State Agent", "Business Rule Agent" }));
        jAgentTypeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAgentTypeComboBoxActionPerformed(evt);
            }
        });
        jAgentTypeComboBox.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jAgentTypeComboBoxPropertyChange(evt);
            }
        });

        jLabel8.setText("Agent Type:");

        jParticipantSetLabel.setText("Participant Set:");

        jPatternTypeLabel.setText("Pattern Type:");

        jAgentPatternTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "Any", "Count", "Value Max", "Value Min", "Value Average", "Relative Min", "Relative Max", "Absence", "Always", "Sometimes", "Not Selected", "Sequence", "Increasing", "Decreasing", "Stable", "Non Increasing", "Non Decreasing", "Mixed", "Min Distance", "Max Distance ", "Average Distance", "Relative Min Distance", "Relative Max Distance", "Relative Average Distance", "Moving in Consistent Direction", "Moving in Mixed Direction", "Stationary", "Moving Towards" }));
        jAgentPatternTypeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAgentPatternTypeComboBoxActionPerformed(evt);
            }
        });

        jRelevanceAssertionTextArea.setColumns(20);
        jRelevanceAssertionTextArea.setLineWrap(true);
        jRelevanceAssertionTextArea.setRows(5);
        jRelevanceAssertScrollPane.setViewportView(jRelevanceAssertionTextArea);

        jRelevanceLabel.setText("Relevance Assertion:");

        jPMatchingComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Single", "Single Deferred", "Unrestricted", "Bounded" }));

        jMatchingLabel.setText("Matching Cardinality Policy");

        jPatternAnnotationLabel.setText("Pattern Annotation:");

        jPatternAnnotationTextArea.setColumns(20);
        jPatternAnnotationTextArea.setLineWrap(true);
        jPatternAnnotationTextArea.setRows(5);
        jPatternAnnoScrollPane.setViewportView(jPatternAnnotationTextArea);

        jParticipantTable.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jParticipantTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Participant", "Event Type", "Repeated Type Policy", "Repeated Type Param", "Consumption Policy", "Consumption Param", "Order Policy", "Order Policy Param"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jParticipantTable.setDragEnabled(true);
        jParticipantTable.getTableHeader().setReorderingAllowed(false);
        jParticipantTableScrollPane.setViewportView(jParticipantTable);

        jDerivedTable.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jDerivedTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Derived", "Event Type", "Derivation Condition", "Derivation Expression"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jDerivedTable.setDragEnabled(true);
        jDerivedTable.getTableHeader().setReorderingAllowed(false);
        jDerivedTableScrollPane.setViewportView(jDerivedTable);

        JPatternAssertionLbl.setText("(Pattern Assertion)");

        jAgentContextComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "Any", "Count", "Value Max", "Value Min", "Value Average", "Relative Min", "Relative Max", "Absence", "Always", "Sometimes", "Not Selected", "Sequence", "Increasing", "Decreasing", "Stable", "Non Increasing", "Non Decreasing", "Mixed", "Min Distance", "Max Distance ", "Average Distance", "Relative Min Distance", "Relative Max Distance", "Relative Average Distance", "Moving in Consistent Direction", "Moving in Mixed Direction", "Stationary", "Moving Towards" }));
        jAgentContextComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAgentContextComboBoxActionPerformed(evt);
            }
        });

        jMatchingLabel1.setText("Matching Cardinality Param");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jAgentOKButton)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jPatternLabel)
                                    .add(jDerivationLabel)
                                    .add(jLabel6)
                                    .add(layout.createSequentialGroup()
                                        .add(JPatternAssertionLbl)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(jAgentSelectionLabel)))
                                .add(18, 18, 18)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jDerivedTableScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 965, Short.MAX_VALUE)
                                    .add(layout.createSequentialGroup()
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                            .add(jAgentPatternTypeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 205, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .add(jPatternTypeLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 94, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                                .add(105, 105, 105))
                                            .add(jParticipantSetLabel))
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(jAgentContextComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 205, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                            .add(jContextLabel))
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                            .add(layout.createSequentialGroup()
                                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                                .add(jPMatchingComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 215, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                                .add(jPMatchingTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 191, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                            .add(layout.createSequentialGroup()
                                                .add(24, 24, 24)
                                                .add(jMatchingLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 185, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .add(jMatchingLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 185, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                                    .add(layout.createSequentialGroup()
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(jRelevanceLabel)
                                            .add(jRelevanceAssertScrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 451, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(layout.createSequentialGroup()
                                                .add(jPatternAnnotationLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 173, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 335, Short.MAX_VALUE))
                                            .add(jPatternAnnoScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 508, Short.MAX_VALUE)))
                                    .add(layout.createSequentialGroup()
                                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 956, Short.MAX_VALUE)
                                        .add(9, 9, 9))
                                    .add(layout.createSequentialGroup()
                                        .add(jLabel8)
                                        .add(33, 33, 33)
                                        .add(jAgentTypeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 286, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 146, Short.MAX_VALUE)
                                        .add(jAgentSubTypeLabel)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(jAgentSubTypeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 324, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                    .add(jAgentSelection, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 965, Short.MAX_VALUE)))))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jParticipantTableScrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 965, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(14, 14, 14)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jAgentTypeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel8)
                            .add(jAgentSubTypeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jAgentSubTypeLabel))
                        .add(20, 20, 20)
                        .add(jAgentSelection, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jAgentSelectionLabel)
                        .add(JPatternAssertionLbl, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jPatternTypeLabel)
                    .add(jContextLabel)
                    .add(jMatchingLabel)
                    .add(jMatchingLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(4, 4, 4)
                        .add(jPatternLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jAgentPatternTypeComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jAgentContextComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jPMatchingComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jPMatchingTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jParticipantSetLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jParticipantTableScrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jRelevanceLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jPatternAnnotationLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jPatternAnnoScrollPane)
                    .add(jRelevanceAssertScrollPane))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jDerivedTableScrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 207, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jAgentOKButton))
                    .add(layout.createSequentialGroup()
                        .add(jDerivationLabel)
                        .addContainerGap())))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    protected void jAgentPatternTypeComboBoxActionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub
		
	}

	private void jAgentTypeComboBoxPropertyChange(PropertyChangeEvent evt) {
		// TODO Auto-generated method stub
		
	}

	private void okButtonHandler(ActionEvent evt) {//GEN-FIRST:event_okButtonHandler
		// validate the uniqness of the agent name
        try{
        	store();
        } catch (UniqueNameException e){
        	this.jAgentIdTextPane.setText(e.toString());
        	return;
        }
        setTitle(vertex.toString());

        MainEditor.vv.repaint();
        dispose();        
    }//GEN-LAST:event_okButtonHandler

    public void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // set the list models
        jAgentContextComboBox.setModel(new javax.swing.DefaultComboBoxModel(Context.getDefinedContexts()));

        jParticipantTable.setModel(new javax.swing.table.AbstractTableModel() {
                Class[] types = new Class [] {
                    java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
                };
                String[] columnNames = new String [] {
                      "Participant", "Event Type", "Repeated Type Policy", "Repeated Type Param", "Consumption Policy", "Consumption Param", "Order Policy", "Order Param"
                 };
        		Object[][] contents = new Object[getPotentialParticipents().size()][columnNames.length];
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }
                @Override
                public boolean isCellEditable(int rowIndex,
                        int columnIndex){
                	return ((columnIndex==0)||(columnIndex==2)||(columnIndex==3)||(columnIndex==4)||(columnIndex==5)||(columnIndex==6)||(columnIndex==7));
                }
				public int getColumnCount() {
					return columnNames.length;
				}
				public String getColumnName(int column){
					return columnNames[column];
				}

				public int getRowCount() {
					return contents.length;
				}

				public Object getValueAt(int rowIndex, int columnIndex) {
					return contents[rowIndex][columnIndex];
				}
				public void setValueAt(Object aValue,
				                       int rowIndex,
				                       int columnIndex){
					contents[rowIndex][columnIndex] = aValue;
				}
            });
        /**
        *
        * The line below is due to a bug in JAVA release, see
        * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4503845
        */
        jParticipantTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        
        jDerivedTable.setModel(new javax.swing.table.AbstractTableModel() {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            String[] columnNames = new String [] {
                  "Derived", "Event Type", "Derivation Condition", "Derivation Expression"
             };
    		Object[][] contents = new Object[getPotentialDerivation().size()][columnNames.length];
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
            @Override
            public boolean isCellEditable(int rowIndex,
                    int columnIndex){
            	return ((columnIndex==0)||(columnIndex==2)||(columnIndex==3));
            }
			public int getColumnCount() {
				return columnNames.length;
			}
			public String getColumnName(int column){
				return columnNames[column];
			}

			public int getRowCount() {
				return contents.length;
			}
			
			public Object getValueAt(int rowIndex, int columnIndex) {
				return contents[rowIndex][columnIndex];
			}
			public void setValueAt(Object aValue,
			                       int rowIndex,
			                       int columnIndex){
				contents[rowIndex][columnIndex] = aValue;
			}
        });
        
        /**
        *
        * The line below is due to a bug in JAVA release, see
        * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4503845
        */
        jDerivedTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        
        jDerivedTable.getColumnModel().getColumn(2).setCellRenderer(new TextAreaRenderer());
        jDerivedTable.getColumnModel().getColumn(3).setCellRenderer(new TextAreaRenderer());
        jDerivedTable.setRowHeight(50);
        
        
        TableColumn synonymPolicy = jParticipantTable.getColumnModel().getColumn(2);
	
	  	JComboBox synonymComboBox = new JComboBox();
	  	for (String s:vertex.policyTypes[vertex.synonymPid]){
	  		synonymComboBox.addItem(s);		
	  	}
	  	synonymPolicy.setCellEditor(new DefaultCellEditor(synonymComboBox));
	  	
        TableColumn consumptionPolicy = jParticipantTable.getColumnModel().getColumn(4);
    	
	  	JComboBox consumptionComboBox = new JComboBox();
	  	for (String s:vertex.policyTypes[vertex.consumptionPid]){
	  		consumptionComboBox.addItem(s);		
	  	}
	  	consumptionPolicy.setCellEditor(new DefaultCellEditor(consumptionComboBox));
        
	    TableColumn orderPolicy = jParticipantTable.getColumnModel().getColumn(6);
	    	
	  	JComboBox orderComboBox = new JComboBox();
	  	for (String s:vertex.policyTypes[vertex.orderPid]){
	  		orderComboBox.addItem(s);		
	  	}
	  	orderPolicy.setCellEditor(new DefaultCellEditor(orderComboBox));
	  	
        populate(vertex);
        
    }//GEN-LAST:event_formComponentShown



	private void jAgentTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAgentTypeComboBoxActionPerformed
        jAgentSubTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(GraphElements.MyVertex.getSubTypeOptions(jAgentTypeComboBox.getSelectedIndex())));
        // inorder for the enable/disable operation to take place at the sub-type
        jAgentSubTypeComboBox.setSelectedIndex(0);
    }//GEN-LAST:event_jAgentTypeComboBoxActionPerformed

    private void jAgentSubTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAgentSubTypeComboBoxActionPerformed
        boolean epatype =((String)jAgentTypeComboBox.getSelectedItem()).compareTo(GraphElements.MyVertex.epa)==0;
        boolean epaDetectPattern =epatype&&((String)jAgentSubTypeComboBox.getSelectedItem()).compareTo(GraphElements.MyVertex.patternDetectionEPA)==0;
    	// Selection
    	jAgentSelection.setVisible(epatype);
    	jAgentSelectionLabel.setVisible(epatype);
    	// Pattern
    	JPatternAssertionLbl.setVisible(epaDetectPattern);
    	jPatternLabel.setVisible(epaDetectPattern);
    	jPatternTypeLabel.setVisible(epaDetectPattern);
    	jAgentPatternTypeComboBox.setVisible(epaDetectPattern);
    	jParticipantSetLabel.setVisible(epaDetectPattern);
    	jAgentContextComboBox.setVisible(epaDetectPattern);
    	jContextLabel.setVisible(epaDetectPattern);
    	jParticipantTableScrollPane.setVisible(epaDetectPattern);
    	jRelevanceLabel.setVisible(epaDetectPattern);
    	jRelevanceAssertScrollPane.setVisible(epaDetectPattern);
    	//jPoliciesLabel.setVisible(epaDetectPattern);


    	jMatchingLabel.setVisible(epaDetectPattern);
    	jPMatchingComboBox.setVisible(epaDetectPattern);
    	jPMatchingTextField.setVisible(epaDetectPattern);

    	jPatternAnnotationLabel.setVisible(epaDetectPattern);
    	jPatternAnnoScrollPane.setVisible(epaDetectPattern);
    	
    	// Derivation
    	jDerivationLabel.setVisible(epatype);
    	jDerivedTableScrollPane.setVisible(epatype);

    }//GEN-LAST:event_jAgentSubTypeComboBoxActionPerformed
    private void jAgentSubTypeComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAgentSubTypeComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jAgentSubTypeComboBox1ActionPerformed

    private void jAgentSubTypeComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAgentSubTypeComboBox5ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jAgentSubTypeComboBox5ActionPerformed

    private void jAgentContextComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAgentContextComboBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jAgentContextComboBoxActionPerformed

    private void keyReleasedHandler(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyReleasedHandler
    	if (evt.getKeyChar()==(char)13)
    		okButtonHandler(null);
    }//GEN-LAST:event_keyReleasedHandler

    private void KeyTypedHandler(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_KeyTypedHandler
    	if (evt.getKeyChar()==(char)13)
    		okButtonHandler(null);
    }//GEN-LAST:event_KeyTypedHandler

    private void jAgentSelectionTextAreaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jAgentSelectionTextAreaMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jAgentSelectionTextAreaMouseClicked



	private void populate(MyVertex agent){  	      
       	//header
    	this.jAgentIdTextPane.setText(agent.getAgentId());
        if (vertex.getAgentType()!=null) 
        	this.jAgentTypeComboBox.setSelectedItem((Object)vertex.getAgentType());
        else
        	this.jAgentTypeComboBox.setSelectedIndex(0);
    	this.jAgentSubTypeComboBox.setSelectedItem(agent.getAgentSubType());
    	   	
    	//selection
    	EPAFiltering filter = agent.getAgentFiltering();
    	if (filter!=null)
    		this.jAgentSelectionTextArea.setText(agent.getAgentFiltering().filteringExpression);
    	
    	
    	//pattern
    	EPAPattern pattern = vertex.getAgentPattern();
    	populateParticipatSetTable(pattern,this.jParticipantTable.getModel());
    	if (pattern!=null){
    		this.jAgentPatternTypeComboBox.setSelectedItem(pattern.patternType);
        	//this.jContextList.setSelectedIndices(PopulateListsUtils.getIDs4Strings(pattern.contexts, MainEditor.contexts));
        	this.jAgentContextComboBox.setSelectedItem(pattern.context);
        	this.jRelevanceAssertionTextArea.setText(pattern.relevanceAssertion);
        	//this.jPSynonymComboBox.setSelectedItem(pattern.synonymPolicy);
        	//this.jPSynonymTextField.setText(pattern.synonymPolicyParam);

        	this.jPMatchingComboBox.setSelectedItem(pattern.matchingPolicy);
        	this.jPMatchingTextField.setText(pattern.matchingPolicyParam);
        	//this.jPConsumptionComboBox.setSelectedItem(pattern.consumptionPolicy);
        	//this.jPConsumptionTextField.setText(pattern.consumptionPolicyParam);  
        	this.jPatternAnnotationTextArea.setText(pattern.annotation);
    	}
    	
    		    	
    	//derivation
    	EPADerivation derivation = vertex.getAgentDerivation();
    	populateDerivationTable(derivation,this.jDerivedTable.getModel());
    }
	private HashSet<String> getPotentialParticipents(){
		HashSet<String> inEdgesEventNames = new HashSet<String>();
		if (MainEditor.g.containsVertex(vertex))
			for (GraphElements.MyEdge e:MainEditor.g.getInEdges(vertex)){
				if (e.getEventIds()==null) continue;
	    		for (int i:e.getEventIds()){
	    			inEdgesEventNames.add(MainEditor.events.get(i).eventTypeIdentifier);
	    		}
	    	}
		return inEdgesEventNames;
	}
    private HashSet<String> getPotentialDerivation() {
		HashSet<String> outEdgesEventNames = new HashSet<String>();
		if (MainEditor.g.containsVertex(vertex))
			for (GraphElements.MyEdge e:MainEditor.g.getOutEdges(vertex)){
				if (e.getEventIds()==null) continue;
	    		for (int i:e.getEventIds()){
	    			outEdgesEventNames.add(MainEditor.events.get(i).eventTypeIdentifier);
	    		}
	    	}
		return outEdgesEventNames;
	}
    private void populateParticipatSetTable(EPAPattern pattern,
    		TableModel tm) {
    	Hashtable<String,ParticipantEvent> participantSetHash = new Hashtable<String,ParticipantEvent>();
    	if (pattern!=null && pattern.participantSet!=null)
    		for (ParticipantEvent e:pattern.participantSet){
    			if (e!=null && e.eventId!=null)
    				participantSetHash.put(e.eventId, e);
    		}
    	
    	int i=0; 
    	for (String s:getPotentialParticipents()){
    		tm.setValueAt(s, i, 1);
    		if (participantSetHash.containsKey(s)){
    			tm.setValueAt((Boolean)true, i, 0);
    			ParticipantEvent pe = participantSetHash.get(s);
    			tm.setValueAt(pe.repeatedTypePolicy, i, 2);   
        		tm.setValueAt(pe.repeatedTypePolicyParam, i, 3);
        		tm.setValueAt(pe.consumptionPolicy, i, 4);
        		tm.setValueAt(pe.consumptionPolicyParam, i, 5);
        		tm.setValueAt(pe.orderPolicy, i, 6);
        		tm.setValueAt(pe.orderPolicyParam, i, 7);
    		}
    		i++;
    	}
	}
    private void populateDerivationTable(EPADerivation derivation,
    		TableModel tm) {
    	Hashtable<String,DerivedEvent> derivationHash = new Hashtable<String,DerivedEvent>();
    	if (derivation!=null && derivation.derivationSet!=null)
    		for (DerivedEvent e:derivation.derivationSet){
    			if (e!=null && e.eventId!=null)
    				derivationHash.put(e.eventId, e);
    		}
    	
    	int i=0; 
    	for (String s:getPotentialDerivation()){
    		tm.setValueAt(s, i, 1);
    		if (derivationHash.containsKey(s)){
    			tm.setValueAt((Boolean)true, i, 0);
    			DerivedEvent pe = derivationHash.get(s);
    			tm.setValueAt(pe.derivationCondition, i, 2);   
        		tm.setValueAt(pe.derivationExpression, i, 3);
    		}
    		i++;
    	}
	}

	private void store() throws UniqueNameException{
       	//header
    	vertex.setAgentId(this.jAgentIdTextPane.getText());
    	vertex.setAgentType((String)this.jAgentTypeComboBox.getSelectedItem());
    	vertex.setAgentSubType((String)this.jAgentSubTypeComboBox.getSelectedItem());
    	   	
    	//selection
    	EPAFiltering filter = new EPAFiltering();
    	filter.filteringExpression = (String)this.jAgentSelectionTextArea.getText();
    	vertex.setAgentFilter(filter);
    	
    	//pattern
    	EPAPattern pattern = new EPAPattern();
    	vertex.setAgentPattern(pattern);
    	pattern.patternType = (String)this.jAgentPatternTypeComboBox.getSelectedItem();
    	storeParticipantSet(pattern,this.jParticipantTable.getModel());
    	pattern.context = (String)this.jAgentContextComboBox.getSelectedItem();

    	pattern.relevanceAssertion = this.jRelevanceAssertionTextArea.getText();
    	//pattern.synonymPolicy = (String)this.jPSynonymComboBox.getSelectedItem();
    	//pattern.synonymPolicyParam = this.jPSynonymTextField.getText();
    	pattern.matchingPolicy = (String)this.jPMatchingComboBox.getSelectedItem();
    	pattern.matchingPolicyParam = this.jPMatchingTextField.getText();
    	//pattern.consumptionPolicy = (String)this.jPConsumptionComboBox.getSelectedItem();
    	//pattern.consumptionPolicyParam = this.jPConsumptionTextField.getText();
    	pattern.annotation = this.jPatternAnnotationTextArea.getText();
    	
    		    	
    	
    	//derivation
    	EPADerivation derivation = new EPADerivation();
    	vertex.setAgentDerivation(derivation);
    	storeDerivedSet(derivation,this.jDerivedTable.getModel());
//    	String derivedEvent = (String)this.jDerivedEvent.getSelectedValue();
//    	if (derivedEvent!=null){
//        	derivation.setDerivedEvent(derivedEvent);
//        	// set up the 4th field
//    		TableModel tm = jPayloadTable.getModel();
//    		for (int i=0; i<derivation.getPayloadLength();i++){
//          		derivation.setDerivedAttr(i,(String)tm.getValueAt(i, 3));
//    		}
//    	}
    	
//    	vertex.setAgentDerivation(jAgentDerivationPane.isVisible()?this.jDerivationTextArea.getText():null);

    }
    
    private void storeParticipantSet(EPAPattern pattern, TableModel tm) {
    	ArrayList<ParticipantEvent> participantSetArrayList = new ArrayList<ParticipantEvent>();
    	for (int i=0;i<tm.getRowCount();i++){
    		if (tm.getValueAt(i, 0)!=null && (Boolean)tm.getValueAt(i, 0)){
        		ParticipantEvent pe = new ParticipantEvent();
        		pe.eventId = (String)tm.getValueAt(i, 1);
        		pe.repeatedTypePolicy = (String)tm.getValueAt(i, 2);
				pe.repeatedTypePolicyParam = (String)tm.getValueAt(i, 3);
	        	pe.consumptionPolicy = (String)tm.getValueAt(i, 4);
	        	pe.consumptionPolicyParam = (String)tm.getValueAt(i, 5);
	        	pe.orderPolicy = (String)tm.getValueAt(i, 6);
	        	pe.orderPolicyParam = (String)tm.getValueAt(i, 7);
	        	
	        	participantSetArrayList.add(pe);
    		}		
    	}	
    	pattern.participantSet = new  ParticipantEvent[participantSetArrayList.size()];
    	int i=0;
    	for (ParticipantEvent pe:participantSetArrayList){
    		pattern.participantSet[i] = pe;
    		i++;
    	}
	}
    
    private void storeDerivedSet(EPADerivation derivation, TableModel tm) {
    	ArrayList<DerivedEvent> derivedSetArrayList = new ArrayList<DerivedEvent>();
    	for (int i=0;i<tm.getRowCount();i++){
    		if (tm.getValueAt(i, 0)!=null && (Boolean)tm.getValueAt(i, 0)){
        		DerivedEvent pe = new DerivedEvent();
        		pe.eventId = (String)tm.getValueAt(i, 1);
        		pe.derivationCondition = (String)tm.getValueAt(i, 2);
				pe.derivationExpression = (String)tm.getValueAt(i, 3);
	        				
	        	derivedSetArrayList.add(pe);
    		}		
    	}	
    	derivation.derivationSet = new  DerivedEvent[derivedSetArrayList.size()];
    	int i=0;
    	for (DerivedEvent pe:derivedSetArrayList){
    		derivation.derivationSet[i] = pe;
    		i++;
    	}
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel JPatternAssertionLbl;
    private javax.swing.JComboBox jAgentContextComboBox;
    private javax.swing.JScrollPane jAgentDerivationPane;
    private javax.swing.JTextPane jAgentIdTextPane;
    private javax.swing.JButton jAgentOKButton;
    private javax.swing.JComboBox jAgentPatternTypeComboBox;
    private javax.swing.JScrollPane jAgentSelection;
    private javax.swing.JLabel jAgentSelectionLabel;
    private javax.swing.JTextArea jAgentSelectionTextArea;
    private javax.swing.JComboBox jAgentSubTypeComboBox;
    private javax.swing.JComboBox jAgentSubTypeComboBox5;
    private javax.swing.JLabel jAgentSubTypeLabel;
    private javax.swing.JComboBox jAgentTypeComboBox;
    private javax.swing.JLabel jContextLabel;
    private javax.swing.JLabel jDerivationLabel;
    private javax.swing.JTextArea jDerivationTextArea;
    private javax.swing.JTable jDerivedTable;
    private javax.swing.JScrollPane jDerivedTableScrollPane;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jMatchingLabel;
    private javax.swing.JLabel jMatchingLabel1;
    private javax.swing.JComboBox jPMatchingComboBox;
    private javax.swing.JTextField jPMatchingTextField;
    private javax.swing.JLabel jParticipantSetLabel;
    private javax.swing.JTable jParticipantTable;
    private javax.swing.JScrollPane jParticipantTableScrollPane;
    private javax.swing.JTable jPartitionParamsTable;
    private javax.swing.JScrollPane jPatternAnnoScrollPane;
    private javax.swing.JLabel jPatternAnnotationLabel;
    private javax.swing.JTextArea jPatternAnnotationTextArea;
    private javax.swing.JLabel jPatternLabel;
    private javax.swing.JLabel jPatternTypeLabel;
    private javax.swing.JScrollPane jRelevanceAssertScrollPane;
    private javax.swing.JTextArea jRelevanceAssertionTextArea;
    private javax.swing.JLabel jRelevanceLabel;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane5;
    // End of variables declaration//GEN-END:variables
    
}
